package com.google.code.openperfmon.web.admin;

import com.google.code.openperfmon.domain.Host;
import com.google.code.openperfmon.service.HostTestingResult;
import com.google.code.openperfmon.service.NonUniqueFieldException;
import com.google.code.openperfmon.service.ServiceFactory;
import com.opensymphony.xwork2.ActionSupport;

@SuppressWarnings("serial")
public class AddEditHostAction extends ActionSupport {
	private Long id;
	private Host host;
	private HostTestingResult testResult;

	public Host getHost() {
		return host;
	}

	public void setHost(Host host) {
		this.host = host;
	}

	public String input() throws Exception {
		if (id == null) {
			host = new Host();
		}
		else {
			host = ServiceFactory.getHostService().getById(id);
		}
		testResult = null;
		return super.input();
	}
	
	public String save() throws Exception {
		try {
			ServiceFactory.getHostService().saveHost(host);
		} 
		catch (NonUniqueFieldException e) {
			addActionError(e.getMessage());
			return INPUT;
		}
		return SUCCESS;
	}
	
	public Long getId() {
		return id;
	}

	public void setId(Long id) {
		this.id = id;
	}
	
	
	public String test() {
		testResult = ServiceFactory.getHostService().testHost(host.getName());
		if (testResult.isResolved()) {
			addActionMessage("Host name successfully resolved.");
			if (testResult.isReached()) {
				addActionMessage("Host reached in " + testResult.getReachTime() + " msec.");
			}
			else {
				addActionMessage("Host is not reachable.");
			}
		}
		else {
			addActionError("host name could not be resolved.");
		}
		return SUCCESS;
	}

	public HostTestingResult getTestResult() {
		return testResult;
	}

}
